package com.bootbo.system.controller;

import com.bootbo.common.annotation.Log;
import com.bootbo.common.domain.Tree;
import com.bootbo.common.utils.MD5Utils;
import com.bootbo.common.utils.R;
import com.bootbo.common.utils.ShiroUtils;
import com.bootbo.system.domain.MenuDO;
import com.bootbo.system.service.MenuService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import static com.bootbo.common.utils.ShiroUtils.getUser;
import static com.bootbo.common.utils.ShiroUtils.getUserId;

/**
 * ClassName index
 * Description
 * Author Layne_Luo
 * Date 2018/7/2 0:07
 */
@Controller
public class LoginController {

    @Autowired
    MenuService menuService;

    @GetMapping("/login")
    String login() {
        return "login";
    }

    @Log("登录")
    @PostMapping("/login")
    @ResponseBody
    R ajaxLogin(String username, String password) {
        password = MD5Utils.encrypt(username, password);
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            return R.ok();
        } catch (AuthenticationException e) {
            return R.error("用户或密码错误");
        }
    }

    @GetMapping({ "/", "", "/index" })
    String Index(Model model) {
        Tree<MenuDO> menuTree = menuService.getSysMenuTree(getUserId());
        model.addAttribute("menus", menuTree);
        model.addAttribute("name", getUser().getName());
        return "index";
    }

    @GetMapping("/logout")
    String logout() {
        ShiroUtils.logout();
        return "redirect:/login";
    }

    @GetMapping("/main")
    String main() {
        return "main";
    }

    @GetMapping("/403")
    String error403() {
        return "403";
    }
}
